using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace researcher
{
  class ResearchAssistant
  {
    private ResearchResult result;
    private bool isResearchInProgress;
    private bool isResearchComplete;
    private string url;
    private ResearchManager manager;

    public ResearchAssistant()
    {
      this.isResearchInProgress = false;
      this.isResearchComplete = false;
    }
    

    public void ResearchUrl()
    {
      this.isResearchInProgress = true;
      result = new ResearchResult();
      this.result.Url = url;
      StringBuilder sb = new StringBuilder();
      byte[] buf = new byte[10240];

      try
      {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();

        string tmp = null;
        int count = 0;

        do
        {
          count = stream.Read(buf, 0, buf.Length);
          if (count > 0)
          {
            tmp = Encoding.ASCII.GetString(buf, 0, count);
            sb.Append(tmp);
          }
        }
        while (count > 0);
      }
      catch (Exception e)
      {
        // Ignore error.
      }

      if (sb.Length > 0)
      {
        this.result.HttpResponse = sb.ToString();
        this.ParseResponse();
      }

      this.isResearchInProgress = false;
      this.isResearchComplete = true;
//      Console.WriteLine("Research is complete for URL: " + url);
      this.manager.ThreadCompleteNotification();
    }


    private void ParseResponse()
    {
      if (this.result != null)
      {
        Match match = Regex.Match(this.result.HttpResponse, @"<title>([^<]*)</title>");
        if (match.Success)
        {
          GroupCollection gc = match.Groups;
          this.result.Title = gc[1].Value;
        }
      }
    }


    public ResearchResult Result
    {
      get { return result; }
      set { result = value; }
    }


    public bool IsResearchInProgress
    {
      get { return isResearchInProgress; }
      set { isResearchInProgress = value; }
    }


    public bool IsResearchComplete
    {
      get { return isResearchComplete; }
      set { isResearchComplete = value; }
    }


    public string Url
    {
      get { return url; }
      set { url = value; }
    }


    public ResearchManager Manager
    {
      get { return manager; }
      set { manager = value; }
    }

  }
}
